package com.smartstate.ems.config;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;

/**
 * @ClassName: CustomAuthenticationKeyGenerator
 * @Description: 自定义token生成规则
 * @author: ruyi
 * @date: 2022/2/28 19:25
 */
@Slf4j
public class CustomAuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {

    private static final String CLIENT_ID = "client_id";
    private static final String SCOPE = "scope";
    private static final String USERNAME = "username";
    // 新增的设备类型，以此来产生不同的token
    private static final String DEVICE_ID = "device_id";

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        log.info("调用自定义的token生成");
        Map<String, String> values = new LinkedHashMap<String, String>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName());
        }
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<String>(authorizationRequest.getScope())));
        }
        String deviceType = authorizationRequest.getRequestParameters().get(DEVICE_ID);
        //不同的端不同的类别，根据ID地址
        if (CharSequenceUtil.isNotBlank(deviceType)) {
            values.put(DEVICE_ID, deviceType);
        }
        // 如果是多租户系统，这里要区分租户ID 条件
        return generateKey(values);
    }
}
